package cn.itcast.core.service.solr;

import java.util.ArrayList;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itcast.common.page.Pagination;
import cn.itcast.core.pojo.product.Product;
import cn.itcast.core.pojo.product.ProductQuery;

/**
 * 索引管理
 * @author 73588
 *
 */
@Service("searchService")
public class SearchServiceImpl implements SearchService {

	@Autowired
	private SolrServer solrServer;
	//带条件的分页（索引库查询）
	public Pagination QuerList(Integer pageNo,String keyword) throws SolrServerException{
		ProductQuery productQuery = new ProductQuery();
		productQuery.setPageNo(Pagination.cpn(pageNo));
		productQuery.setPageSize(6);
		StringBuilder params = new StringBuilder();
		
		SolrQuery solrQuery = new SolrQuery ();
		//关键字查询
		/*solrQuery.set("q", "name_ik"+keyword);*/
		solrQuery.setQuery(keyword);
		params.append("keyword=").append(keyword);
		//过滤条件
		//高亮
		//排序
		solrQuery.addSort("price", ORDER.asc);
		//分页
		solrQuery.setStart(productQuery.getStartRow());
		solrQuery.setRows(productQuery.getPageSize());
		//指定查询域
		solrQuery.set("fl", "id,name_ik,price,url");
		//制定默认域
		solrQuery.set("df", "name_ik");
		//执行查询
		QueryResponse query = solrServer.query(solrQuery);
		//获得结果集
		SolrDocumentList list = query.getResults();
		
		//为了页面遍历方便创建个对象的结果集
		ArrayList<Product> arrayList = new ArrayList<>();
		for (SolrDocument doc : list) {
			//创建对象封装数据
			Product product = new Product();
			//id
			String id = (String) doc.get("id");
			product.setId(Long.parseLong(id));
			//名称
			String name = (String) doc.get("name_ik");
			product.setName(name);
			//价格
			Float price = (Float) doc.get("price");
			product.setPrice(price);
			//url图片
			String url = (String) doc.get("url");
			product.setImgUrl(url);
			
			//arrayList添加对象
			arrayList.add(product);
		}
		//获得查询总条数
		long numFound = list.getNumFound();
		Pagination pagination = new Pagination();
		pagination.setPageNo(productQuery.getPageNo());
		pagination.setPageSize(productQuery.getPageSize());
		pagination.setTotalCount((int)numFound);
		pagination.setList(arrayList);
		String url="/Search";
		//回显页面
		pagination.pageView(url, params.toString());
		return pagination;
	}
	
}
